<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax文件下载</title>
    <script src="/js/jquery/jquery.min.js"></script>
</head>
<body>

<fieldset>
    <legend>文件下载</legend>
    <div>
        <button type="button" id="download_1_id" style="margin-right: 25px;">下载方式1</button>
        <button type="button" id="download_2_id">下载方式2</button>
    </div>
</fieldset>


<script type="text/javascript">
    $(function() {
        $("#download_1_id").click(function() {
            downloadSubmit("/ajax/download/yml");
        })
        $("#download_2_id").click(function() {
            downloadSubmit("/ajax/download/class");
        })
    });

    function downloadSubmit(url) {
        $.ajax({
            url: url,
            type: 'get',
            dataType: "*",
            xhrFields: {
                responseType: "blob",
            },
            success: function (result , status , xhr) {
                const blob = new Blob([result], {
                    type: xhr.getResponseHeader("Content-Type"),
                });
                debugger;
                let fileName = xhr.getResponseHeader("Content-Disposition").replace('attachment; filename="' , "").replace('"' , "");
                const link = document.createElement("a");
                link.href = window.URL.createObjectURL(blob);
                link.download = decodeURI(fileName);
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            },
            error: function (xhr, status, error) {
                alert("文件下载失败，状态码：" + status.statusCode + "，参考信息：" + status.statusText);
            }
        });
    }

</script>

</body>
</html>